<?php

namespace App\Http\Controllers\Test;


use App\Http\Controllers\Controller;
use App\Models\Goods;
use App\Models\GoodsCate;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class TestController extends Controller
{


    // 测试

    // 测试缓存key
    public function key()
    {

        $where = [['channel_type', 'in', ['long', 'short']], ["verify", '=', 1], ['is_draft', '=', 0], ['is_complain', '=', 0], ['is_user', '=', 1,], ['is_original', '=', 1,],];
        //$where[] = ['channel_type', '=', 1];

        // 会改变where  => ok
        $where = [["verify", '=', 1], ['is_draft', '=', 0],];
        // 会改变where  => ok
        $where[] = ["comment_no" => DB::raw("comment_no+221")];
        $where[] = DB::raw("id in  (1, 2, 3,4,5,8)");


        //var_dump(gettype( DB::raw("id in  (1, 2, 3,4,5,8)")));
        //var_dump(gettype($where));
        // 不会改变生成的key  => error
        /*$where[] = function ($qq) {
            $qq = $qq->whereNotIn('id', [1, 2, 3,4,5,6]);
        };*/

        $where[] = [function ($qq) {
            $qq = $qq->whereNotIn('id', [1, 2, 3, 4, 5, 6]);
        }];

        $where[] = function ($qq) {
            $qq = $qq->whereNotIn('sdsid', [1, 2, 3, 4, 5, 6]);
        };


        $where[] = function ($query) {
            $columns = ['name', 'title'];
            $type    = '=';
            if ($type == 'like') {
                $value = '%haha%';
            }
            foreach ($columns as $_column) {
                $query = $query->orWhere($_column, $type, $value);
            }
        };
        $where[] = [function ($query) {
            $columns = ['name', 'title'];
            $type    = '=';
            if ($type == 'like') {
                $value = '%haha%';
            }
            foreach ($columns as $_column) {
                $query = $query->orWhere($_column, $type, $value);
            }
        }];

        // 判断是否可以生成一个变化的 key 方案1
        // 如果数组中有对象，则 表示不能生成一个变化的key，这个时候不能生成缓存  => 错误
        $objectNumber = count(array_filter($where, 'is_object'));
        var_dump($objectNumber);

        // 组合key
        $order = 'id DESC';
        $args  = compact('where', 'order');
        $key   = $this->cacheKey('table', 'show', $args);
        var_dump($key);

        // 判断key里面是否有对象的字符串  \Closure::__set_state(array(____)   方案2

        // PHP 8.0+：使用 str_contains()（区分大小写）
        if (str_contains($key, '\Closure::__set_state(array(____)')) {
            echo "包含";
        } else {
            echo "不包含";
        }
    }

    // 生成缓存key
    public function cacheKey($tagName, $key, $param = [])
    {
        //$tagName  = $this->name;  // 模型名称
        $store    = 'store';
        $preKey   = $store . '.' . $tagName . '.' . $store . '_' . $tagName . '_' . $key;
        $cacheKey = '';

        // 制作key
        foreach ($param as $ke => $item) {
            if (empty($item)) {
                continue;
            }
            $cacheKey .= '_' . $ke . '_';
            $cacheKey .= is_array($item) ? var_export($item, 1) : $item;
        }
        $cacheKey = str_replace(['.', ' '], '_', $cacheKey);
        $cacheKey = str_replace(["\r\n", "\r", "\n"], "", $cacheKey);  // 删除换行

        return $preKey . $cacheKey;
    }

    // 返回列表数据
    // http://www.enshop.com/test/test/lists
    public function lists()
    {
        $page    = 1;
        $rows    = 15;
        $cate_id = 1;

        // 参数
        $is_get_propose = 0;  // 是否获取推荐商品
        $is_get_number  = 0;  // 获取商品的指定个数


        $order = "id DESC";
        $cache = ['status' => 1];
        $where = [['status', '=', 1]];
        if ($cate_id) {
            // 如果 where 含有 function 生成的缓存key，不会起作用，所以会导致重复的key，则缓存无效
            $cateDb = new GoodsCate();
            $childs = $cateDb->getChildIds($cate_id);
            //var_dump('语句：',$cateDb->getLastSql());
            //var_dump('子栏目',$childs);
            if ($childs) {
                $cache['cate_id'] = $childs;
                // 条件
                $where[] = [
                    function ($qq) use ($childs) {
                        $qq = $qq->whereIn('cate_id', $childs);
                    },
                ];
            } else {
                $cache['cate_id'] = $cate_id;
                // 条件
                $where[] = ['cate_id', '=', $cate_id];
            }
        }
        if ($is_get_propose) {
            // 没有推荐 按销量排序
            $order = "sale_no DESC";
            $cache = false;
        }


        // 如果 where 含有 function 生成的缓存key，不会起作用，所以会导致重复的key，则缓存无效
        //  现在已经判断，如果  where 中有对象，则不在缓存


        // 模型 和 查询
        $model = new Goods();
        // 数据整理
        if ($is_get_number) {
            $list   = $model->getListCache($cache, $where, $is_get_number, $order);
            if ($list === false) {
                die($model->getError());
            }
            $result = ['list' => $list];
        } else {
            $result = $model->listPageCache($cache, $where, $page, $rows, $order);
            if ($result === false) {
                die($model->getError());
            }
        }
        var_dump('语句：',$model->getLastSql());


        return $result;
    }

    // 栏目
    // http://www.enshop.com/test/test/cate
    public function cate(){
        $cateDb = new GoodsCate();
        $cates = $cateDb->getListCache([],[],9999);
        var_dump($cates);
    }

    //  查询测试
    // http://www.shop.com/test/test/one
    public function one()
    {
        /*$request = $this->request;
        $fullUrl = $request->url(true);
        var_dump($fullUrl);

        // 或者，仅获取域名部分
        $domain = $request->getHttpHost();
        var_dump($domain);
        $domain = $request->host();
        var_dump($domain);
        $domain = $request->getScheme();
        var_dump($domain);
        $domain = $request->schemeAndHttpHost();
        var_dump($domain);*/

        $info = (new User())->where('id', 1)->first();
        //var_dump($info->toArray());


        //var_dump($info);

        return $info;
    }


}


